import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from "rxjs/Observable";
import {DialogProvider} from "@providers/dialog";
import {StorageProvider} from "@providers/storage";
import {env} from "@env/environment";

/*
  Generated class for the HttpProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class HttpProvider {

  constructor(private http: HttpClient,
              private dialogService: DialogProvider,
              private storageService: StorageProvider) {
  
  }



  get(url: string, params?: any, options?: any): Observable<any> {
    if (!options) {
      let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
      options = {headers: headers};
    }
    if (params) {
      // params.has("SessionID")
      if (!params.hasOwnProperty("SessionID") || !params["SessionID"]) {
        let userInfo = this.storageService.read('userInfo');
        // params.set("SessionID", UserInfo["SessionID"]);
        userInfo && (params['SessionID'] = userInfo["SessionID"]);
        !userInfo && (params["rmstoken"] = env.rmstoken);
      }
      params['CLIENT'] = "PHONE";
      options["params"] = params;
    }
    return this.parseResponse(this.http.get(this.formatUrl(url), options));
  }

  post(url: string, body: any = null, options?: any): Observable<any> {
    if (!options) {
      let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
      options = {headers: headers};
    }
    if (!(body instanceof String)) {
      if (!body.hasOwnProperty("SessionID") || !body["SessionID"]) {
        let userInfo = this.storageService.read('userInfo');
        // params.set("SessionID", UserInfo["SessionID"]);
        userInfo && (body['SessionID'] = userInfo["SessionID"]);
        !userInfo && (body["rmstoken"] = env.rmstoken);
      }
      body['CLIENT'] = "PHONE";
      body = this.buildURLSearchParams(body);
    }
    return this.parseResponse(this.http.post(this.formatUrl(url), body.toString(), options));
  }

  private parseResponse(observable: Observable<Object>): Observable<any> {
    return Observable.create((observer) => {
      //this.nativeService.showLoading();
      observable.subscribe(res => {
        //this.nativeService.hideLoading();
        let message = this.extractData(res);
        let msgId = message["MSGID"] || '';

        let body = message;

        if (msgId == "E") {
          let msg;
          try {
            msg = JSON.stringify(message)
          } catch (e) {
            msg = message;
          }
          body = message["MESSAGE"] || msg;
          observer.error(body);
        } else {
          try {
            body = JSON.parse(body['MESSAGE'])
          } catch (e) {
            body = message;
          }

          observer.next(body);
          observer.complete();
        }
      }, err => {
        this.requestFailed(err);//处理请求失败
        observer.error(this.handleError(err));
      });
    });
  }

  private extractData(res) {
    try {
      let body = res;
      return body || {};
    } catch (err) {
      return {"MSGID": "E", "MESSAGE": res.text()};
    }
  }

  private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof HttpErrorResponse) {
      errMsg = `${error.status} - ${error.statusText || ''} ${error.error.text}`;
    } else {
      errMsg = error.MESSAGE ? error.MESSAGE : error.toString();
    }
    return errMsg;
  }

  /**
   * 处理请求失败事件
   * @param url
   * @param err
   */
  private requestFailed(err: HttpErrorResponse) {
    let msg = '';
    try {
      let error = err.error;
      msg = error.text || '请求发生异常';

      let status = err.status;
      if (status === 0) {
        window.open(env.app_serve_url);
      } else if (status === 404) {
        msg = '请求失败，未找到请求地址';
      } else if (status === 500) {
        msg = '请求失败，服务器出错，请稍后再试';
      }
    } catch (e) {
      msg = '请求发生异常';
    }
    this.dialogService.showToast(msg);
  }

  private buildURLSearchParams(paramMap: Map<String, any> | any): URLSearchParams {
    let params = new URLSearchParams;
    if (!paramMap) {
      return params;
    }
    for (let key in paramMap) {
      let val = paramMap[key];
      params.set(key, val);
    }
    if (!params.hasOwnProperty("SessionID")) {
      let userInfo = this.storageService.read('userInfo');
      userInfo && (params.set('SessionID', userInfo["SessionID"]));
    }
    params.set('CLIENT', "PHONE");
    return params;
  }

  /**
   * url中如果有双斜杠替换为单斜杠
   * 如:http://127.0.0.1:8080//api//demo.替换后http://88.128.18.144:8080/api/demo
   * @param url
   * @returns {string}
   */
  private formatUrl(url): string {
    if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
      url = env.app_serve_url + url;
    }
    let index = url.indexOf('//') + 2;
    return url.substring(0, index) + url.substring(index).replace(/\/\//g, '/');
  }
}
